package com.markerhub.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;

public class OKXRSITradingBot {

    private static final String API_KEY = "1b8506df-84bc-472d-a5cc-c30a8baf13d6";
    private static final String API_SECRET = "94FDBCF142FA69EF5FE1A958F44FEA63";
    private static final String API_PASSPHRASE = "CCvv414616@";
    private static final String BASE_URL = "https://www.okx.com/api/v5/";

    private static final OkHttpClient client = new OkHttpClient();
    private static final Gson gson = new Gson();

    public static void main(String[] args) {
        String symbol = "BTC-USDT";
        while (true) {
            try {
                double rsi = getRSI(symbol, "1H", 14);
                if (rsi < 30) { // 超卖，买入
                    System.out.println("RSI超卖，买入");
                    //placeOrder(symbol, "buy", "0.001");
                } else if (rsi > 70) { // 超买，卖出
                    System.out.println("RSI超买，卖出");
                   // placeOrder(symbol, "sell", "0.001");
                }
                Thread.sleep(60000); // 每分钟检查一次
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 获取RSI指标
    private static double getRSI(String symbol, String timeframe, int period) throws IOException {
        String url = BASE_URL + "market/candles?instId=" + symbol + "&bar=" + timeframe + "&limit=" + (period + 1);
        Request request = new Request.Builder().url(url).get().build();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        JsonArray candles = gson.fromJson(responseBody, JsonObject.class).getAsJsonArray("data");

        double[] closes = new double[candles.size()];
        for (int i = 0; i < candles.size(); i++) {
            closes[i] = Double.parseDouble(candles.get(i).getAsJsonArray().get(4).getAsString());
        }

        double avgGain = 0, avgLoss = 0;
        for (int i = 1; i < closes.length; i++) {
            double change = closes[i] - closes[i - 1];
            if (change > 0) {
                avgGain += change;
            } else {
                avgLoss += Math.abs(change);
            }
        }
        avgGain /= period;
        avgLoss /= period;

        double rs = avgGain / avgLoss;
        return 100 - (100 / (1 + rs));
    }

    // 下单函数
    private static void placeOrder(String symbol, String side, String size) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String url = BASE_URL + "trade/order";
        String timestamp = Instant.now().toString();
        JsonObject params = new JsonObject();
        params.addProperty("instId", symbol);
        params.addProperty("tdMode", "cash");
        params.addProperty("side", side);
        params.addProperty("ordType", "market");
        params.addProperty("sz", size);

        String message = timestamp + "POST" + "/api/v5/trade/order" + params.toString();
        String signature = sign(message, API_SECRET);

        RequestBody body = RequestBody.create(params.toString(), MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("OK-ACCESS-KEY", API_KEY)
                .addHeader("OK-ACCESS-SIGN", signature)
                .addHeader("OK-ACCESS-TIMESTAMP", timestamp)
                .addHeader("OK-ACCESS-PASSPHRASE", API_PASSPHRASE)
                .addHeader("Content-Type", "application/json")
                .build();

        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

    // 生成签名
    private static String sign(String message, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hash);
    }
}